<template>
    <div class="cart-container">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <input type="checkbox" v-model="item.selected" @change="updateTotalPrice" />
            <div class="cart-item-info" @click="viewProduct(item.product)">
                <img :src="item.product.imageUrl" alt="商品图片" class="cart-item-image" />
                <span style="margin-left: 20px;">{{ item.product.name }}</span>
                <span style="margin-left: 20px; color: #999;">X &nbsp;{{ item.quantity }}</span>
            </div>
            <span style="color: red;">{{ item.totalPrice | currency }}</span>
        </div>
        <div class="cart-footer">
            <span>总价: {{ totalPrice | currency }}</span>
            <div>
                <span :style="{ color: totalPrice > (userInfo?.balance || 0) ? 'red' : 'black' }">
                    余额: {{ (userInfo?.balance || 0) | currency }}
                </span>
                <button style="margin-left: 50px;" @click="checkout">结算</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { get, post } from "../until/request";
import Swal from 'sweetalert2';

const router = useRouter();

const cartItems = ref([]);  // 购物车商品
const totalPrice = ref(0);  // 总价
const userInfo = ref({ balance: 0 }); // 初始化用户信息为一个包含默认余额的对象
const cartIds = ref([]); // 获取选中商品的购物车ID

onMounted(() => {
    const storedData = localStorage.getItem('login');
    if (storedData) {
        userInfo.value = JSON.parse(storedData);
        try {
            getCart();// 获取购物车信息
        } catch (error) {
            console.error("Error fetching cart data:", error);
        }
    }
});

// 获取购物车信息
async function getCart() {
    const response = await get("/user/getCart", { userId: userInfo.value.id });
    console.log(response);
    if (response && response.code === 1) {
        cartItems.value = response.data.map(item => ({
            ...item,
            selected: false // 初始化为未选中
        }));
    }
}
// 更新总价
function updateTotalPrice() {
    totalPrice.value = cartItems.value
        .filter(item => item.selected)
        .reduce((sum, item) => sum + item.totalPrice, 0);
}

// 结算
async function checkout() {
    if (totalPrice.value > userInfo.value.balance) {
        Swal.fire({
            title: '余额不足',
            text: '您的余额不足以支付所选商品的总价。',
            icon: 'error',
            confirmButtonText: '确定'
        });
        return;
    }

    const selectedItems = cartItems.value.filter(item => item.selected);
    cartIds.value = selectedItems.map(item => item.id);  // 获取选中商品的购物车ID
    console.log(cartIds.value);
    if (selectedItems.length === 0) {
        Swal.fire({
            title: '提示',
            text: '请选择至少一个商品进行结算',
            icon: 'warning',
            confirmButtonText: '确定'
        });
        return;
    }
    // 处理结算逻辑
    console.log("结算商品:", selectedItems);
    // return;

    // 显示加载圈
    Swal.fire({
        title: '处理中',
        text: '请稍候...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    try {
        const response = await post("/user/settlement", {
            userId: userInfo.value.id,
            cartIds: cartIds.value,
            totalPrice: totalPrice.value
        });
        // 关闭加载圈
        Swal.close();
        if (response && response.code === 1) {
            getCart(); // 获取购物车信息
            Swal.fire({
                title: '提示',
                text: '付款成功',
                icon: 'success',
                confirmButtonText: '确定'
            });
            // 更新用户余额
            userInfo.value.balance -= totalPrice.value;
            localStorage.setItem('login', JSON.stringify(userInfo.value));
        } else {
            Swal.fire({
                title: '提示',
                text: '结算失败',
                icon: 'error',
                confirmButtonText: '确定'
            });
        }
    } catch (error) {
        console.error("Error during checkout:", error);
    }
}

// 查看商品详情
function viewProduct(product) {
    // 将产品信息存储到 localStorage
    localStorage.setItem('selectedProduct', JSON.stringify(product));
    router.push({ name: 'ProductDetail' });
}
</script>

<style lang="scss" scoped>
.cart-container {
    padding: 20px;
    background-color: #f9f9f9;
}

.cart-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ddd;

    input[type="checkbox"] {
        width: 20px;
        height: 20px;
        margin-right: 30px;
    }

    .cart-item-info {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: start;

        .cart-item-image {
            width: 100px;
            height: auto;
            object-fit: cover;
        }
    }
}

.cart-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
</style>